Page({
  data: {
    inventory: [],
    beizhu: [],
    attention: [],
    currentView: 'inventory',
    db: null
  },

  onLoad: function() {
    this.initCloudDatabase();
  },

  initCloudDatabase: function() {
    const db = wx.cloud.database();
    this.setData({ db });
    this.getInventoryData();
    this.getBeizhuData();
    this.loadAttention();
  },

  loadAttention: function() {
    const db = this.data.db;
    db.collection('attention').get().then(res => {
      const attention = res.data.map(item => {
        const timestamp = new Date(item.timestamp);
        const formattedTime = this.formatDate(timestamp);
        return {
          ...item,
          timestamp: formattedTime
        };
      });
      this.setData({
        attention
      });
    }).catch(err => {
      console.error(err);
    });
  },

  formatDate(timestamp) {
    const year = timestamp.getFullYear();
    const month = String(timestamp.getMonth() + 1).padStart(2, '0');
    const day = String(timestamp.getDate()).padStart(2, '0');
    const hours = String(timestamp.getHours()).padStart(2, '0');
    const minutes = String(timestamp.getMinutes()).padStart(2, '0');
    const seconds = String(timestamp.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  },

  getInventoryData: function() {
    const db = this.data.db;
    const inventoryCollection = db.collection('inventory');
    inventoryCollection.get().then(res => {
      this.setData({
        inventory: res.data
      });
    }).catch(err => {
      console.error(err);
    });
  },

  getBeizhuData: function() {
    const db = this.data.db;
    const beizhuCollection = db.collection('beizhu');
    beizhuCollection.get().then(res => {
      this.setData({
        beizhu: res.data
      });
    }).catch(err => {
      console.error(err);
    });
  },

  handleInventoryChange: function(e) {
    const index = e.currentTarget.dataset.index;
    const newNum = parseInt(e.detail.value);
    const updatedInventory = this.data.inventory.map((item, idx) => {
      if (idx === index) {
        return { ...item, num: newNum };
      }
      return item;
    });
    this.setData({ inventory: updatedInventory });

    const db = this.data.db;
    const inventoryCollection = db.collection('inventory');
    inventoryCollection.doc(updatedInventory[index]._id).update({
      data: {
        num: newNum
      }
    }).then(res => {
      console.log('Inventory updated:', res);
    }).catch(err => {
      console.error(err);
    });
  },

  handleStatusChange: function(e) {
    const index = e.currentTarget.dataset.index;
    const updatedBeizhu = this.data.beizhu.map((item, idx) => {
      if (idx === index) {
        return { ...item, status: "处理" };
      }
      return item;
    });
    this.setData({ beizhu: updatedBeizhu });

    const db = this.data.db;
    const beizhuCollection = db.collection('beizhu');
    beizhuCollection.doc(updatedBeizhu[index]._id).update({
      data: {
        status: "处理"
      }
    }).then(res => {
      console.log('Status updated:', res);
    }).catch(err => {
      console.error(err);
    });
  },

  handleDeleteAttention: function(e) {
    const { _id } = e.currentTarget.dataset;
    const db = this.data.db;
    if (_id) {
      db.collection('attention').doc(_id).remove().then(() => {
        this.loadAttention();
      }).catch(err => {
        console.error(err);
      });
    } else {
      console.error('Invalid document ID');
    }
  },
  showInventory: function() {
    this.setData({ currentView: 'inventory' });
  },

  showBeizhu: function() {
    this.setData({ currentView: 'beizhu' });
  },

  showAttention: function() {
    this.setData({ currentView: 'attention' });
  }
});